const g_password_salt = "1a2b3c4d";
const g_storage = window.localStorage || {};

function g_setRedirect(uri) {
  g_storage['redirectUri'] = uri;
}

function g_getRedirectAndClear() {
  const uri = g_storage['redirectUri'];
  delete g_storage['redirectUri'];
  return uri;
}

function g_mix_password(pass) {
  const mixed = pass.substring(0, 3) +
    g_password_salt.substring(0, 4) +
    pass.substring(3, pass.length) +
    g_password_salt.substring(3, 8);
  return md5(mixed);
}

function g_getQueryString(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}

function g_ajaxError(error) {
  const resp = error.response;
  console.log(resp);
  if (resp.status === 401) {
    console.log(window.location)
    const uri = window.location.pathname + window.location.search;

    /*const params = new URLSearchParams();
    params.append("uri", uri)
    axios.post("/login/cacheRedirect", params).finally(() => {
      window.location.href = "/login";
    });*/

    g_setRedirect(uri);
    window.location.href = "/login.html";
  }
}

function g_formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

